// 当前文件用来存放管理员和用户共用的东西

const BookModule = require("../database/book");
const sequelize = require("../database/index");

// 分页查询
async function Paging(req, res, next) {
  // 获取查询参数
  const queryParam = req.query;
  const currentPage = queryParam.pages || 1;
  const offset = 10 * (currentPage - 1);
  // 查询数据库
  try {
    let result = await BookModule.findAll({
      offset,
      limit: 10,
    });
    // 转成josn数据返回至客户端
    result = result.map((item) => {
      return item.toJSON();
    });
    // console.log('result', result);
    res.status(200).json({
      msg: "查询数据成功",
      info: result,
    });
  } catch (error) {
    next({ msg: "分页查询数据库中数据出错", error });
  }
}

// 查询历史记录
async function queryHistory(req, res) {
  // 1. 获取传过来的参数
  const query = req.query;
  console.log(query);
  let { user_name } = query;
  // 通过原生的SQL语句进行子查询
  const queryParams = "book_id,book_name,author,publisher,place,price";

  // 获取未归还的书籍信息
  const [queryResultOne] = await sequelize.query(
    `SELECT ${queryParams} from books WHERE book_id IN(SELECT book_id FROM borrows WHERE user_name='${user_name}' AND is_return=0)`
  );
  // 获取已经归还的书籍信息
  const [queryResultTwo] = await sequelize.query(
    `SELECT ${queryParams} from books WHERE book_id IN(SELECT book_id FROM borrows WHERE user_name='${user_name}' AND is_return=1)`
  );
  const queryResult = {
    user_name,
    hasBeenReturned: queryResultTwo,
    didNotReturn: queryResultOne,
  };
  res.status(200).json({
    msg: "查询成功",
    queryResult,
  });
}

module.exports = {
  Paging,
  queryHistory,
};
